package model

import (
	"qabx.net/safe-app-center/pkg/utils"
	"time"
)

type TblDeviceInfo struct {
	Id         int64     `json:"id" xorm:"pk autoincr"`
	DeviceMac  string    `json:"device_mac"`
	OsName     string    `json:"os_name"`
	DeviceName string    `json:"device_name"`
	CreateAt   time.Time `json:"create_at" xorm:"created"`
	UpdateAt   time.Time `json:"update_at" xorm:"updated"`
}

func (s *TblDeviceInfo) AddAndUpdateDeviceInfoByMac() (id int64, err error) {
	table := "tbl_device_info"
	dbClient, _ := utils.GetDbClient()
	dbClient.QueryParam = utils.QueryParam{
		Table:    table,
		Resource: &id,
		Cols:     []string{"id"},
		Where:    "device_mac = '" + s.DeviceMac + "'",
	}
	_, err = dbClient.GetOne()
	if err != nil {
		return
	}
	if id == 0 {
		dbClient.InsertParam = utils.InsertParam{
			Table:    table,
			Resource: s,
		}
		_, err = dbClient.Insert()
		id = s.Id
	} else {
		fields := make([]string, 0)
		if s.DeviceName != "" {
			fields = append(fields, "device_name")
		}
		if s.OsName != "" {
			fields = append(fields, "os_name")
		}
		dbClient.UpdateParam = utils.UpdateParam{
			Table:    table,
			Id:       id,
			Cols:     fields,
			Resource: s,
			//Where: "id = " + strconv.FormatInt(id, 10),

		}
		_, err = dbClient.Update()
	}

	return
}
